package com.simple.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * json转换工具
 * 
 * @author USER
 * 
 */
public class JsonConvertUtil {

	/**
	 * 对象转JSON
	 * 
	 * @param jsoncallback
	 * @param object
	 */
	public static void toJSONString(HttpServletResponse response, String jsoncallback, Object object) {
		JSONObject json = new JSONObject(object);
		PrintWriter writer = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		try {
			writer = response.getWriter();
			if (StringUtils.isEmpty(jsoncallback)) {
				writer.print(json.toString());
			} else {
				writer.print(jsoncallback + "(" + json.toString() + ")");
			}
			writer.close();
		} catch (IOException e) {
		}
	}

	/**
	 * 集合转JSON
	 * 
	 * @param jsoncallback
	 * @param value
	 */
	@SuppressWarnings({ "rawtypes" })
	public static void toJSONString(HttpServletResponse response, String jsoncallback, Collection value) {
		JSONArray json = new JSONArray();
		json.put(value);
		PrintWriter writer = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		try {
			writer = response.getWriter();
			if (StringUtils.isEmpty(jsoncallback)) {
				writer.print(json.toString());
			} else {
				writer.print(jsoncallback + "(" + json.toString() + ")");
			}
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String toJSONString(String jsoncallback, Object object) {
		JSONObject jsonObject = new JSONObject(object);
		String retJson = jsonObject.toString();
		if (!StringUtils.isEmpty(jsoncallback)) {
			retJson = jsoncallback + "(" + retJson + ")";
		}
		return retJson;
	}

	public static boolean isJson(String value) {
		try {
			new JSONObject(value);
		} catch (JSONException e) {
			return false;
		}
		return true;
	}

	/**
	 * 从json中获取key对应的String(不存在返回空)
	 * 
	 * @param json
	 * @param key
	 * @return
	 */
	public static String getString(JSONObject json, String key) {
		if (json == null || StringUtils.isEmpty(key)) {
			return null;
		}
		if (json.has(key)) {
			return json.getString(key);
		}
		return null;
	}
}
